import React, { Component } from 'react'
import { Link } from 'react-router-dom';
import { Row, Col ,Breadcrumb, Modal,Button, Upload,Icon,Table} from 'antd';
import { Form } from '../../common/form';
import api from '../../../api/api';
import { connectRouter } from '../../../mixins/router';
import './GroupOrderInsuranceDetail.less'
import { testPermission } from '../../common/HasPermission';
import url from 'url';
import querystring from 'querystring';
import history from '../../../history'
const StatusChoices = [{
  value: 10,
  label: '待确认',
}, {
  value: 20,
  label: '投保中',
}, {
  value: 30,
  label: '已承保',
}, {
  value: 40,
  label: '已完成',
}];
class GroupOrderInsuranceDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
        id:'',
        productId:'', // 产品id
        data:{},
        loading:false,
        serverTime:'',
        insureBtnExpired:false, // 投保人员变更按钮是否过期
        insureModalVisible:false,
        addFileList:[], // 批增清单
        subFileList:[], // 批减清单
        uploadResult:{}, // 批增结果
        verificationModal:false // 校验结果弹窗

    }
  }
  async componentDidMount(){
    this.init()
  }

  init= async ()=>{
    let id = this.props.match.params.id;
    const urlObj = url.parse(this.props.location.search);
    const query = querystring.parse(urlObj.query);
    let productId = query.productId;
    let data = await api.getGroupInsuranceDetail(id)
    // 判断按钮是否过期
    let insureBtnExpired = false
    if(data.createDate){
      let createDate = new Date(data.createDate)
      let year = createDate.getFullYear()
      let month = createDate.getMonth()
      let expireDate = new Date(year+'/'+(month+2))
      let now = new Date()
      if(now >= expireDate){
        insureBtnExpired = true
      }
    }else{
      insureBtnExpired = true
    }
    this.setState({
      id,
      productId,
      data,
      loading:true,
      insureBtnExpired
    })
  }
  getStatusLable = (status)=>{
    let target = StatusChoices.find(item=>{return +item.value === +status})
    return target && target.label || ''
  }
  downloadList = ()=>{
    if(testPermission('groupInsurance.export')){
      window.open(`/_api/groupInsurance/${this.state.id}/insuranceTeamOrderInfo`)
    }else{
      Modal.error({
        title:'提示',
        content:'权限不够'
      })
    }
  }
  // 下载批增批减
  downloadAddSub = (name)=>{
    window.open(`/_api/oss/download?objectName=`+name)
  }
  // 批减模板下载
  downloadSubTemplate =()=>{
    window.open(
      'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/crm-web/groupOrderInsurance/%E5%9B%A2%E9%99%A9%E6%89%B9%E5%87%8F%E6%A8%A1%E6%9D%BF.xlsx',
    );
  }
  formatObjectName = (objectName)=>{
    if(objectName){
      let index = objectName.indexOf('/')
      return objectName.slice(index+1)
    }
  }
  get backToIndex() {
    if (this.props.router.query.r && this.props.router.query.r.indexOf('/GroupOrderInsurance') === 0) {
      return this.props.router.query.r;
    } else {
      return '/GroupOrderInsurance';
    }
  }
  // 投保人员变更
  changeServiceUser=()=>{
    let productId = this.state.productId
    if(productId){
      this.setState({
        insureModalVisible:true
      })
    }else{
      Modal.error({
        title:'错误提示',
        content:'产品id不存在，请返回列表页重新进入详情',
        okText:'确定',
        cancelText:'取消',
        onOk:()=>{
          history.push(`/GroupOrderInsurance`);
        },
        onCancel:()=>{

        }
      })
    }
  }
  addDataFn = ({file})=>{
    // 批增导入数据
    this.setState({
      addFileList:[file]
    })
    let response = file.response
    if(response){
      if(response.code === 0){
        this.setState({
          uploadResult: response.data,
        })
        if(response.data.errors && response.data.errors.length > 0){
          this.setState({
            insureModalVisible:false,
            verificationModal: true
          })
        }
      }else{
        this.setState({
          addFileList:[],
          uploadResult:{}
        })
        Modal.confirm({
          title:'上传提示',
          content:response.message || '上传文件失败, 请重新上传' ,
          okText:'确定',
          cancelText:'取消',
        })
      }
    }
  }
  subDataFn= ({file})=>{
    // 批减导入数据
    this.setState({
      subFileList:[file]
    })
    let response = file.response
    if(response){
      if(response.code === 0){
        this.setState({
          uploadResult: response.data,
        })
        if(response.data.errors && response.data.errors.length > 0){
          this.setState({
            insureModalVisible:false,
            verificationModal: true
          })
        }
      }else{
        this.setState({
          subFileList:[],
          uploadResult:{}
        })
        Modal.confirm({
          title:'上传提示',
          content:response.message || '上传文件失败, 请重新上传' ,
          okText:'确定',
          cancelText:'取消',
        })
      }
    }
  }

  // 删除批增文件
  removeAddFile =()=>{
    this.setState({
      addFileList:[],
      uploadResult:{}
    })
  }
  // 删除批减文件
  removeSubFile =()=>{
    this.setState({
      subFileList:[],
      uploadResult:{}
    })
  }

  submitToService = () => {
    this.setState({
      loading:true
    })
    let { productId,addFileList,subFileList } = this.state
    let form = new FormData()
    if(addFileList.length > 0){
      form.append('add',addFileList[0].originFileObj)
    }
    if(subFileList.length > 0){
      form.append('del',subFileList[0].originFileObj)
    }
    // fetch(`/_api/groupInsurance?productId=${productValue[0]}`,{
    fetch(`/_api/groupInsurance/batchOperation?groupOrderId=${this.state.id}`,{
      body:form,
      method:'POST'
    }).then(res=>{
      console.log('res:',res)
      return res.json()
    }).then(data=>{
      this.setState({
        loading:false
      })
      if(data.code ===0 ){
        // 提交的数据有问题
        if(data.data && data.data.length>0){
          this.setState({
            uploadResult:{
              count:data.data.length,
              errors:data.data
            },
            insureModalVisible:false,
            verificationModal:true
          })
        }else{
          // 提交正确，且没问题,清空上传内容，返回列表
          this.setState({
            insureModalVisible:false
          })
          this.init()
        }
      }else{
        this.setState({
          uploadResult:{},
          insureModalVisible:false
        })
        Modal.confirm({
          title:'提交确认',
          content:data.message || '提交数据至服务器报错，请稍后重试',
          okText:'确定',
        })
        return
      }
    }).catch((err)=>{
      this.setState({
        insureModalVisible:false
      })
      Modal.error({
        title:'提交确认',
        content: '导入出错，请联系管理员',
        okText:'确定',
      })

      this.setState({
        loading:false
      })
    })
  }

  verificationCancel=()=>{
    this.setState({
      insureModalVisible:true,
      verificationModal:false
    })
  }

  // 点击校验确定按钮
  verificationOk = ()=>{
    // 点击校验确定按钮
    this.setState({
      insureModalVisible:true,
      verificationModal:false
    })
  }

  goServiceDetail = (rowData)=>{
    window.open(`/patientInsuranceDetail/${rowData.id}?r=${encodeURIComponent(this.props.router.fullPath)}`,'_blank');
  }

  closeInsureModal=()=>{
    this.setState({
      insureModalVisible:false
    })
  }


  render(){
    let { id,data,insureBtnExpired,insureModalVisible,productId,verificationModal,addFileList ,subFileList,uploadResult  } = this.state
    const apiUrl = `_api/groupInsurance/excel/validate?productId=${productId}&groupOrderId=${id}`;
    return (
      <div className="goid">
        <Breadcrumb className="breadcrumb-box">
          <Breadcrumb.Item>
            <Link to={this.backToIndex}>团险订单管理</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>团险订单详情</Breadcrumb.Item>
        </Breadcrumb>
        <div className="goi-main">

          <div className="m-item">
          {/* <div className="title">团险订单详情</div> */}
            <div className="title detail-title">
              <div>投保单流水号：{data.sequenceNo}</div>
              <div className="detail-status">{ this.getStatusLable(data.status) }</div>
            </div>
            <div className="detail">
              <div className="d-content">
                <Row gutter={16}>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      投保单流水号：{data.sequenceNo}
                    </div>
                  </Col>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      保单号：{data.policyNo}
                    </div>
                  </Col>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      投保主体：{data.insurerName}
                    </div>
                  </Col>
                </Row>


                <Row gutter={16}>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      保险公司：{data.insuranceCompany}
                    </div>
                  </Col>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      保险产品：{data.productName}
                    </div>
                  </Col>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      投保方案代码：{data.suitCode}
                    </div>
                  </Col>
                </Row>


                <Row gutter={16}>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      保险期间：{data.startDate} 至 {data.endDate}
                    </div>
                  </Col>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      保险期限：1年
                    </div>
                  </Col>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      缴费频次：月缴
                    </div>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      缴费方式：转账或支票
                    </div>
                  </Col>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      缴费期数：{data.peroid}
                    </div>
                  </Col>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      操作人：{data.createrInfo}
                    </div>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col className="gutter-row" span={8}>
                    <div className="gutter-box">
                      操作时间：{data.createDate}
                    </div>
                  </Col>

                </Row>
              </div>
            </div>

            <div className="title">被保人信息</div>
            <div className="patient">
              <Row gutter={16}>
                <Col className="gutter-row" span={8}>
                  <div className="gutter-box">
                    被保人数：{data.count}
                  </div>
                </Col>
                <Col className="gutter-row" span={8}>
                  <div className="gutter-box">
                    有效会员数：{data.insuredCount}
                  </div>
                </Col>
                <Col className="gutter-row" span={8}>
                  <div className="gutter-box">
                    末次缴费日期：{data.lastPaymentDate}
                  </div>
                </Col>
              </Row>
              {
                // 承包中 已承保，已完成，才能下载承包清单
                (data.status === 20 || data.status === 30 || data.status === 40) ? (
                  <Row gutter={16}>
                    <Col className="gutter-row" span={8}>
                      <div className="gutter-box goi-listfile" onClick={() => {this.downloadList(data.originObjectName)}}>
                        承保清单：<span className="goi-list-name">{ this.formatObjectName(data.originObjectName)}</span>
                      </div>
                    </Col>
                  </Row>
                ) : ''
              }
              <Row>
                <div>
                  <Button onClick={this.changeServiceUser}  type="primary" disabled={insureBtnExpired}>
                    投保人员变更
                  </Button>
                </div>
                <div style={{marginTop:'20px'}}>
                  {
                    data.batchDataRecords && data.batchDataRecords.length> 0 && data.batchDataRecords.map(item=>{
                      return (<div className="gutter-box goi-listfile" onClick={() => {this.downloadAddSub(item.objectName)}}>
                        {item.type === 1 ? '批增清单.xls' : '批减清单.xls'}：<span className="goi-list-name">{ this.formatObjectName(data.originObjectName)}</span>
                      </div>)
                    })
                  }
                </div>
              </Row>
            </div>
            <div className="title">团险订单流水</div>
            <div className="timeline">
              {
                data.logs && data.logs.length > 0 && data.logs.map((item,index)=>{
                  return <div key={index}>{item.createDate}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{item.content}</div>
                })
              }
            </div>

            <Modal
              title="投保人员变更"
              visible={insureModalVisible}
              onOk={this.submitToService}
              onCancel={this.closeInsureModal}
            >
              <div className="i">
                <Upload
                  name="file"
                  onChange={this.addDataFn}
                  action={ apiUrl+'&type=1' }
                  fileList={addFileList}
                  onRemove={this.removeAddFile}
                  >
                  <Button>
                    <Icon type="upload" /> 批增导入
                  </Button>
                </Upload>
              </div>
              <div style={{marginTop:"20px"}}>
                <Upload
                  name="file"
                  onChange={this.subDataFn}
                  action={ apiUrl+'&type=2' }
                  fileList={subFileList}
                  onRemove={this.removeSubFile}
                  >
                  <Button>
                    <Icon type="upload" /> 批减导入
                  </Button>
                </Upload>
              </div>
              <div style={{marginTop:"20px"}}>
                <span style={{color:"blue",textDecoration:"underline",cursor:"pointer"}} onClick={this.downloadSubTemplate}>批减模板下载</span>
              </div>
              <div className="import-red" style={{marginTop:'20px',display:'flex',alignItems:'center'}}><Icon type="info-circle" style={{color:'#F59A23',fontSize:'20px',marginRight:"20px"}}/>批增模板同投保清单模板</div>
            </Modal>

            {/* 弹窗 */}
            <Modal
              title="导入校验"
              visible={verificationModal}
              wrapClassName="vertical-center-modal"
              onCancel={this.verificationCancel}
              width="800px"
              footer={[
                <Button key="submit" type="primary" size="large" onClick={this.verificationOk}>
                  确定
                </Button>,
              ]}
            >
              {/* <div className="vertical-center-modal-bgi-title">被保人服务产品与投保产品不一致，请修改后重新导入！</div> */}
              <div className="vertical-center-modal-bgi-tip">以下会员数据校验不通过：</div>
              <Table dataSource={uploadResult.errors}  pagination={false} bordered>
                <Table.Column
                  dataIndex="orderNo"
                  title="服务订单号"
                  key="orderNo"
                  onCellClick={(rowData) => this.goServiceDetail(rowData)}
                  render={(text)=>{
                    return <span className="clickable">{text}</span>
                  }}
                />
                <Table.Column
                  title="服务包名称"
                  dataIndex="packageName"
                  key="packageName"
                />
                <Table.Column
                  title="被保人名称"
                  dataIndex="insuredName"
                  key="insuredName"
                />
                <Table.Column
                  title="被保人身份证号"
                  dataIndex="insuredIdCard"
                  key="insuredIdCard"
                />
                <Table.Column
                  title="校验结果"
                  dataIndex="message"
                  key="message"
                />
              </Table>
            </Modal>

          </div>
        </div>
      </div>
    )
  }
}
export default connectRouter(GroupOrderInsuranceDetail);
